package com.yxt.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.CommUtil;
import com.yxt.common.sys.StringUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.model.Function;
import com.yxt.service.DivisionService;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	private static final int HELP_MENU = Menu.FIRST+1;
	private static final int SETTING_MENU = Menu.FIRST + 2;
	private static final int EXIT_MENU = Menu.FIRST + 3;
	
	private GridView gridview;
	private DivisionService service = new DivisionService(this);
	
	private static final Map<String, String> ICO_URL = new HashMap<String, String>();
	static {
		ICO_URL.put("R.id.rain", String.valueOf(R.drawable.fun_rain));
		ICO_URL.put("R.id.water", String.valueOf(R.drawable.fun_water));
		ICO_URL.put("R.id.salt", String.valueOf(R.drawable.fun_shang));
		ICO_URL.put("R.id.soil", String.valueOf(R.drawable.fun_shang));
		ICO_URL.put("R.id.project", String.valueOf(R.drawable.fun_proj));
		ICO_URL.put("R.id.weather", String.valueOf(R.drawable.fun_weather));
		ICO_URL.put("R.id.report", String.valueOf(R.drawable.fun_report));
		ICO_URL.put("R.id.yuntu", String.valueOf(R.drawable.fun_yuntu));
		ICO_URL.put("R.id.tfdata", String.valueOf(R.drawable.fun_taifeng));
		ICO_URL.put("R.id.search", String.valueOf(R.drawable.fun_search));
		ICO_URL.put("R.id.address", String.valueOf(R.drawable.fun_tongxun));
		ICO_URL.put("R.id.knowledge", String.valueOf(R.drawable.fun_zhishi));
	}
	
	//加载Activity
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.main);   //软件activity的布局		
		ActivityStackControlUtil.add(this); //注销Activity
		TextView lblTitle = (TextView)findViewById(R.id.lblTitle);
		lblTitle.setText(getAppTitle());
		lblTitle.setTextSize(20);
		initComponent();
	}

	//设置标题
	public String getAppTitle() {
		Map<String,String> template = CommConstant.Main.TEMPLATES.get(CommConstant.Main.CURRENT_TEMPLATE_CODE);
		String title;
		if(template != null){
			title = template.get("apptitle");
			//如果模板中存在APPTITLE则用此标题,如果不存在则判断rootarea是否为空，如果不为空则用当前地区加默认标题,如果为空则用默认标题
			if (StringUtil.isEmpty(title)) {
				String area = template.get("rootarea");
				if (StringUtil.isEmpty(area)) {
					title = getString(R.string.app_name);
				} else {
					String code = area.substring(0,2);
					if (code.equals("00")) {
						title = getString(R.string.app_name);
					} else {
						title = service.getDivisionByCode(code).getName()+getString(R.string.app_name);
					}
				}
			}
		}
		else{
			title = "全国水情易信通";
		}
		return title;
	}
	
	private void initComponent(){
		//
		gridview = (GridView) findViewById(R.id.gdvFuc);
		final List<Map<String, String>> menus = new ArrayList<Map<String, String>>();
		SharedPreferences settings = getSharedPreferences(CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		String template = settings.getString(CommConstant.Login.APP_TEMPLATE_CODE, "");
		Map<String,Map<String,String>> functions = CommConstant.Main.FUNCTIONS.get(template);
		//如果不存在此模板，则跳转到模板设置页面
		if (functions== null || functions.size() == 0) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SystemSettingActivity.class);
			startActivity(intent);
		} else {
			//获取 MPHOTO RADAR
			Map<String, Function> defines = CommUtil.getAppFunction(this);
			Iterator<Entry<String,Map<String,String>>> iterator = functions.entrySet().iterator();
			while(iterator.hasNext()) {
				Entry<String,Map<String,String>> entry = iterator.next();
				String key = entry.getKey();
				if (defines.containsKey(key)) {
					Function function = defines.get(key);
					Map<String, String> value = new HashMap<String, String>();
					value.put("itemImage", ICO_URL.get(function.getIco()));
					value.put("itemText", function.getName());
					value.put("itemUrl", function.getUrl());
					value.putAll(entry.getValue());
					//
					menus.add(value);
				} else {
					System.out.println(key);
				}
			}
			FunctionTableAdapter saMenuItem = new FunctionTableAdapter(this, menus,	R.layout.lstfunc, new String[] { "itemImage", "itemText" },	new int[] { R.id.itemImage, R.id.itemText });
			gridview.setAdapter(saMenuItem);
			gridview.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> adapter, View view,
						int index, long arg3) {
					Intent intent = new Intent();
					Map<String,String> data = menus.get(index);
					try {
						intent.setClass(getApplicationContext(),Class.forName(data.get("itemUrl")));
						intent.putExtra("itemId", data.get("id"));
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行FLAG设置 
						startActivity(intent);
					} catch (ClassNotFoundException e) {
						Log.e("未找到相关的类", e.getMessage());
					}
				}
			});
		}
	}
	
	public class FunctionTableAdapter extends SimpleAdapter {
		private int itemHeight = 0;
		
		public FunctionTableAdapter(Context context, List<Map<String,String>> data,int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			//计算每项的高度
			double size = data.size();
			int lines = (int)Math.ceil(size / CommConstant.Main.DEFAULT_ITEM_COUNT);
			int height = CommConstant.screenHeight - lines * CommConstant.Main.DEFAULT_ITEM_HEIGHT;
			if (height < 0 ){
				height = 0;
			}
			itemHeight = height / (lines * 4);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			TextView lblTop = (TextView)view.findViewById(R.id.lblTop);
			lblTop.setHeight(itemHeight);
			TextView lblBottom = (TextView)view.findViewById(R.id.lblBottom);
			lblBottom.setHeight(itemHeight);
			return view;
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {  
		if(keyCode == KeyEvent.KEYCODE_BACK){
			new AlertDialog.Builder(MainActivity.this).setTitle("提示")
			.setMessage("是否确定要退出")
			.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface,int i) {
							ActivityStackControlUtil.finishProgram();
						}
					})
			.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface,int i) {
							
						}
					}).show();
			return false;
		}
		return super.onKeyDown(keyCode, event); 
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, HELP_MENU, 1, R.string.menu_help);
		menu.add(0, SETTING_MENU, 2, R.string.menu_setting);
		menu.add(0, EXIT_MENU, 2, R.string.menu_exit);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		switch (item.getItemId()) {
			case HELP_MENU:
				intent.setClass(getApplicationContext(), SystemHelpActivity.class);
				startActivity(intent);	
				return true;
			case SETTING_MENU:
				intent.setClass(getApplicationContext(), SystemSettingActivity.class);
				startActivity(intent);	
				return true;
			case EXIT_MENU:
				ActivityStackControlUtil.finishProgram();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
	
}